package com.yiwyn;


import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import com.yiwyn.domain.User;
import org.openjdk.jmh.annotations.*;
import org.openjdk.jmh.runner.Runner;
import org.openjdk.jmh.runner.RunnerException;
import org.openjdk.jmh.runner.options.Options;
import org.openjdk.jmh.runner.options.OptionsBuilder;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@BenchmarkMode(Mode.AverageTime)
@OutputTimeUnit(TimeUnit.NANOSECONDS)
@Warmup(iterations = 1, time = 1, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 10, time = 1, timeUnit = TimeUnit.SECONDS)
@State(Scope.Benchmark)
@Fork(value = 1)
public class PerfMain {


    public User user = new User() {{
        setName("yiwyn");
        setId(5);
    }};

    @Benchmark
    public Object javaCode() {
        if (user.getId() > 2) {
            return true;
        }
        return false;
    }

    @Benchmark
    public Object aviatorCode() {
        // 创建执行器
        AviatorEvaluatorInstance engine = AviatorEvaluator.getInstance();
        // 表达式

        String expression = "if (user.id > 2) {\n" +
                "            return true;\n" +
                "        }\n" +
                "        return false;";

        Map<String, Object> map = new HashMap<>();
        map.put("user", user);

        Expression exp = engine.compile(expression, true);

        Object result = exp.execute(map);

        return result;
    }


    public static void main(String[] args) throws RunnerException {
        Options options = new OptionsBuilder()
                .include(PerfMain.class.getSimpleName())
                .build();
        new Runner(options).run();
    }


}
